package com.store.app.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
/**
 * 一些与包处理的工具类
 */
public class PackageUtils {
	private static final String TAG = "PackageUtils";
	/**
	 * 通过"包名"打开外部程序
	 * @param packageName 程序的packageName
	 * @param notInstalledDo 如果外部程序没有安装则在主线程中运行该回调
	 */
	public static void openOutSideApp(Context context, String packageName) {
		openOutSideApp(context, packageName,"",null);
	}
	
	/**
	 * 通过"包名"打开外部程序
	 * @param packageName 程序的packageName
	 * @param appName app的名字
	 * @param notInstalledDo 如果外部程序没有安装则在主线程中运行该回调
	 */
	public static void openOutSideApp(Context context, String packageName, String appName, Runnable notInstalledDo) {
		if (context == null ) {
			Log.v(TAG,String.format("context is null"));
			return ;
		}
		if (TextUtils.isEmpty(packageName)) {
			Log.v(TAG,String.format("packageName is null"));
			return ;
		}
		
		if (TextUtils.isEmpty(appName)) {
			appName = " app ";
		}
		
		if (context instanceof Activity) {
			final Activity activity = (Activity) context;
			final Intent intent = activity.getPackageManager().getLaunchIntentForPackage(packageName);
			if (intent != null) {
				Log.v(TAG,String.format("intent 启动%s", appName));
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						activity.startActivity(intent);
					}
				});
			}else{
				Log.v(TAG,String.format("打开%s异常", appName));
				if (notInstalledDo!=null) {
					activity.runOnUiThread(notInstalledDo);
				}
			}
		}else {
			Log.v(TAG,String.format("非 Activity 打开 intent 启动 %s" , appName));
		}
	}
}
